<!DOCTYPE html>
<html lang="en">
<head>
	<meta charset="UTF-8">
	<title>135-动画-匀速动画-透明度优化.html</title>
	<style>
		*{
			margin: 0;
			padding: 0;
		}
		#box{
			position: absolute;
			top: 50px;
			left: 0px;
			width: 100px;
			height: 100px;
			background: red;
			opacity: 0.2;
		}
		.line{
			width: 1px;
			height: 400px;
			background: #000;
			position: absolute;
			top: 0;
			left: 400px;
		}
	</style>
</head>
<body>
	<button id="btn">开始动画</button>
	<div id="box"></div>
	<div class="line"></div>
</body>
<script>
	var oBtn = document.getElementById('btn');
	var oBox = document.getElementById('box');
	var timer = 0;
	oBtn.onclick = function(){
		clearInterval(timer);
		var iSpeed = 0;
		timer = setInterval(function(){
			var currentVal = parseFloat(getComputedStyle(oBox,false)["opacity"]);
			currentVal = Math.round(currentVal*100);
			if(currentVal<100){
				iSpeed = 3;
			}else{
				iSpeed = -3;
			}
			if(Math.abs(100 -currentVal) < Math.abs(iSpeed)){
				oBox.style.opacity = 1;
				clearInterval(timer);
			}else{
				oBox.style.opacity = (currentVal + iSpeed)/100;
			}
			console.log(currentVal);
		},30)
	}
</script>
</html>